const fs = require('fs');
const path = require('path');
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const cors = require('cors');
const morgan = require('morgan');
const winston = require('winston');
const apiRoutes = require('./server/routes/api');
const config = require('./server/config/config');
const websocketService = require('./server/services/wsService');
const connectDB = require('./server/database');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// 连接到 MongoDB
connectDB();

// 创建 log 目录（如果不存在）
const logDir = path.join(__dirname, 'log');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

// 创建 winston logger
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: path.join(logDir, 'error.log'), level: 'error' }),
    new winston.transports.File({ filename: path.join(logDir, 'combined.log') })
  ]
});

// 在生产环境下，将日志输出到控制台
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple(),
  }));
}

// 使用 morgan 中间件只记录 /api 路由的日志
app.use(morgan('combined', { 
  skip: (req) => !req.path.startsWith('/api'), // 只记录 /api 路由
  stream: {
    write: (message) => logger.info(message.trim())
  }
}));

// 使用 morgan 记录错误日志
app.use((err, req, res, next) => {
  logger.error(err.message);
  next(err);
});

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public'))); // 提供静态文件服务
app.use('/api', apiRoutes); // 使用 API 路由

// WebSocket 连接处理
wss.on('connection', (ws) => websocketService.handleConnection(ws, wss));

websocketService.startHeartbeat(); // 启动心跳检测

// 启动服务器
server.listen(config.PORT, () => {
  logger.info(`服务器正在运行，访问 http://localhost:${config.PORT}`);
});
